package net.sk.china.city.talk.service.impl.wechat;

import com.alibaba.fastjson.JSONObject;
import net.sk.china.city.talk.constants.WeChatConstants;
import net.sk.china.city.talk.service.wechat.WechatNewService;
import net.sk.china.city.talk.service.wechat.WeixinPublicService;
import net.sk.china.common.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * WeixinPublicServiceImpl 接口实现
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2018-2024 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2024/2/21 10:08
 * // +----------------------------------------------------------------------
 */

@Service
public class WeixinPublicServiceImpl implements WeixinPublicService {


    private final RedisUtil redisUtil;

    private final WechatNewService wechatNewService;

    @Autowired
    public WeixinPublicServiceImpl(RedisUtil redisUtil, WechatNewService wechatNewService) {
        this.redisUtil = redisUtil;
        this.wechatNewService = wechatNewService;
    }


    /**
     * 获取公众号自定义菜单
     * @return Object
     */
    @Override
    public Object getCustomizeMenus() {
        Object list = redisUtil.get(WeChatConstants.REDIS_PUBLIC_MENU_KEY);
        String empty = "";
        if (list == null || list.equals(empty)) {
            //如果没有， 去读取
            JSONObject tagsList = wechatNewService.getPublicCustomMenu();
            redisUtil.set(WeChatConstants.REDIS_PUBLIC_MENU_KEY, tagsList);
            list = tagsList;
        }
        return list;
    }

    /**
     * 保存自定义菜单
     * @param data 菜单json
     * @return Boolean
     */
    @Override
    public Boolean createMenus(String data) {
        Boolean create = wechatNewService.createPublicCustomMenu(data);
        if (!create) {
            return create;
        }
        // 清除历史缓存
        if (redisUtil.exists(WeChatConstants.REDIS_PUBLIC_MENU_KEY)) {
            redisUtil.delete(WeChatConstants.REDIS_PUBLIC_MENU_KEY);
        }
        return Boolean.TRUE;
    }

    /**
     * 删除自定义菜单
     * @return Boolean
     */
    @Override
    public Boolean deleteMenus() {
        Boolean delete = wechatNewService.deletePublicCustomMenu();
        if (!delete) {
            return delete;
        }
        // 清除历史缓存
        if (redisUtil.exists(WeChatConstants.REDIS_PUBLIC_MENU_KEY)) {
            redisUtil.delete(WeChatConstants.REDIS_PUBLIC_MENU_KEY);
        }
        return Boolean.TRUE;
    }
}
